package it.getta.vicinometro.utils;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.TextView;

public class FadingTextView extends TextView {

	private Animation mFadeInAnimation;
	private Animation mFadeOutAnimation;
	private boolean mIsAnimating = false;
	private boolean mIsFadingIn = false;
	private boolean mIsFadingOut = false;
	
	public boolean isFadingIn() {
		return mIsFadingIn;
	}

	public void setFadingIn(boolean isFadingIn) {
		this.mIsFadingIn = isFadingIn;
	}

	public boolean isFadingOut() {
		return mIsFadingOut;
	}

	public void setFadingOut(boolean isFadingOut) {
		this.mIsFadingOut = isFadingOut;
	}

	private static final int ANIMATION_DURATION = 250;
	
	public FadingTextView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public FadingTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public FadingTextView(Context context) {
		super(context);
		init();
	}
	
	private void init() {
		setVisibility(View.INVISIBLE);
		mFadeInAnimation = new AlphaAnimation(0.00f, 1.00f);
		mFadeInAnimation.setDuration(ANIMATION_DURATION);
		mFadeInAnimation.setAnimationListener(new AnimationListener() {
			
			@Override
			public void onAnimationStart(Animation arg0) {
				mIsAnimating = true;
				mIsFadingIn = true;
				if (!isShown()) {
					setVisibility(View.VISIBLE);
				}
			}
			
			@Override
			public void onAnimationRepeat(Animation arg0) {
				mIsAnimating = true;
			}
			
			@Override
			public void onAnimationEnd(Animation arg0) {
				mIsAnimating = false;
				mIsFadingIn = false;
			}
		});
		mFadeOutAnimation = new AlphaAnimation(1.00f, 0.00f);
		mFadeOutAnimation.setDuration(ANIMATION_DURATION);
		mFadeOutAnimation.setAnimationListener(new AnimationListener() {
			
			@Override
			public void onAnimationStart(Animation animation) {
				mIsAnimating = true;
				mIsFadingOut = true;
			}
			
			@Override
			public void onAnimationRepeat(Animation animation) {
				mIsAnimating = true;
			}
			
			@Override
			public void onAnimationEnd(Animation animation) {
				if (isShown()) {
					setVisibility(View.INVISIBLE);
				}
				mIsAnimating = false;
				mIsFadingOut = true;
			}
		});
	}
	
	public void fadeIn() {
		startAnimation(mFadeInAnimation);
	}
	
	public void fadeOut() {
		startAnimation(mFadeOutAnimation);
	}

	public boolean isAnimating() {
		return mIsAnimating;
	}

	public void setAnimating(boolean isAnimating) {
		this.mIsAnimating = isAnimating;
	}

}
